<template>
  <el-row>
    <el-row>
      <el-col :span="32" style="text-align: left">
        <div class="block">
          <span class="demonstration">选择月份范围</span>
          <el-date-picker
              v-model="date_range"
              type="monthrange"
              align="center"
              size="large"
              @change="selectChange"
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              value-format="yyyy-MM"
              :picker-options="pickerOptions">
          </el-date-picker>
          <el-select
              v-model="select_models"
              multiple
              filterable
              collapse-tags
              @change="selectChange"
              style="margin-left: 20px;width: 150px;"
              placeholder="设备型号">
            <el-option
                v-for="item in product_models"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
          &
          <el-select
              v-model="select_sub_models"
              multiple
              filterable
              collapse-tags
              @change="selectChange"
              style="width: 150px;"
              placeholder="次级设备型号">
            <el-option
                v-for="item in sub_product_models"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>

          <el-select
              v-model="select_feedback_type"
              multiple
              filterable
              collapse-tags
              @change="selectChange"
              style="margin-left: 20px; width: 150px;"
              placeholder="反馈单类型">
            <el-option
                v-for="item in feedback_types"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
          <el-select
              v-model="select_numbers"
              multiple
              filterable
              collapse-tags
              @change="selectChange"
              style="margin-left: 20px;width: 150px;"
              placeholder="机器编号">
            <el-option
                v-for="item in equipment_numbers"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
          <el-select
              v-model="select_versions"
              multiple
              filterable
              collapse-tags
              @change="selectChange"
              style="margin-left: 20px;"
              placeholder="系统版本">
            <el-option
                v-for="item in system_versions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>
    <el-divider></el-divider>
    <div id="feedback-figure-2"></div>
  </el-row>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios'

axios.defaults.baseURL = '/api'
export default {
  data() {
    return {
      data: {},
      select_versions: [],
      system_versions: [],
      select_numbers: [],
      equipment_numbers: [],
      product_models: [],
      sub_product_models: [],
      select_models: ['SR2000'],
      select_sub_models: [],
      select_feedback_type: [],
      feedback_types: [],
      date_range: [],
      option: {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        toolbox: {
          feature: {
            dataView: {show: true, readOnly: false},
            magicType: {show: true, type: ['line', 'bar']},
            myTool: {
                show: true,
                title: 'export data',
                icon: 'path://path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891', // 使用 SVG 路径作为图标
                onclick: function () {
                    this.exportChartData(this.select_versions)
                }.bind(this)
            },
            saveAsImage: {show: true}
          }
        },
        legend: {
          data: ['手术台数', '客诉数量', '客诉率']
        },
        xAxis: [
          {
            type: 'category',
            data: ['2024/1', '2024/2', '2024/3', '2024/4', '2024/5', '2024/6', '2024/7', '2024/8', '2024/9', '2024/10', '2024/11', '2024/12'],
            axisPointer: {
              type: 'shadow'
            },
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '数量',
            min: 0,
            max: 500,
            interval: 50,
            axisLabel: {
              formatter: '{value} 次'
            }
          },
          {
            type: 'value',
            name: '客诉率',
            min: 0,
            max: 25,
            interval: 5,
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '手术台数',
            type: 'bar',
            tooltip: {
              valueFormatter: function (value) {
                return value + ' 次';
              }
            },
            data: []
          },
          {
            name: '客诉数量',
            type: 'bar',
            tooltip: {
              valueFormatter: function (value) {
                return value + ' 条';
              }
            },
            data: []
          },
          {
            name: '客诉率',
            type: 'line',
            yAxisIndex: 1,
            tooltip: {
              valueFormatter: function (value) {
                return value + ' ';
              }
            },
            data: []
          }
        ]
      },
      chart: null,
      pickerOptions: {
        shortcuts: [{
          text: '本月',
          onClick(picker) {
            picker.$emit('pick', [new Date(), new Date()]);
          }
        }, {
          text: '今年至今',
          onClick(picker) {
            const end = new Date();
            const start = new Date(new Date().getFullYear(), 0);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setMonth(start.getMonth() - 6);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  created() {
    this.initDatePicker();
    this.query_product_models();
    this.query_feedback_type();
    this.query_equipment_numbers();
    this.query_system_versions();
    this.initPlot();
  },
  methods: {
    exportChartData(versions) {
      axios.post('/feedback/figure/2/data', {
            params: {
              date_list: this.date_range,
              product_models: this.select_models,
              sub_product_models: this.select_sub_models,
              feedback_type: this.select_feedback_type,
              equipment_numbers: this.select_numbers,
              system_versions: versions
            }
          }
      ).then(
          response => {
            let blob = new Blob([response.data], {type: 'text/csv; charset=utf-8'});
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = `data_versions.csv`;
            if (versions.length === 1) {
              link.download = `data_${versions[0]}.csv`;
            }
            link.click();
            window.URL.revokeObjectURL(link.href);
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
          })
    },
    initDatePicker() {
      let end = new Date();
      let start = new Date();
      start.setMonth(start.getMonth() - 6);
      start = start.getFullYear() + '-' + (start.getMonth()+1);
      end = end.getFullYear() + '-' + (end.getMonth()+1);
      this.date_range = [start, end];
    },
    query_feedback_type() {
      axios.get('/feedback/product/types/').then(
          response => {
            let data = JSON.parse(response.data).data;
            this.feedback_types = []
            data.forEach(item => {
              this.feedback_types.push(
                  {
                    value: item,
                    label: item
                  }
              )
            })
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
            this.feedback_types = [];
          })
    },
    query_system_versions() {
      axios.get('/feedback/system/versions/', {
        params: {
          product_models: this.select_models
          }
        }
      ).then(
          response => {
            let data = JSON.parse(response.data).data;
            this.system_versions = []
            console.log(data);
            data.forEach(item => {
              if (item !== '') {
                this.system_versions.push(
                    {
                      value: item,
                      label: item
                    }
                );
              }
              this.select_versions.push(item);
            })
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
            this.system_versions = [];
          })
    },
    query_equipment_numbers() {
      axios.get('/feedback/equipment/numbers/', {
        params: {
          product_models: this.select_models
          }
        }
      ).then(
          response => {
            let data = JSON.parse(response.data).data;
            this.equipment_numbers = []
            data.forEach(item => {
              this.equipment_numbers.push(
                  {
                    value: item,
                    label: item
                  }
              )
            })
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
            this.equipment_numbers = [];
          })
    },
    query_product_models() {
      axios.get('/feedback/product/models/').then(
          response => {
            let data = JSON.parse(response.data).data;
            this.product_models = []
            this.sub_product_models = []
            data.forEach(item => {
              this.product_models.push(
                  {
                    value: item,
                    label: item
                  }
              )
              this.sub_product_models.push(
                  {
                    value: item,
                    label: item
                  }
              )
            })
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
            this.product_models = [];
            this.sub_product_models = [];
          })
    },
    initPlot() {
      axios.post('/feedback/figure/2/', {
            params: {
              date_list: this.date_range,
              product_models: this.select_models,
              sub_product_models: this.select_sub_models,
              feedback_type: this.select_feedback_type,
              equipment_numbers: this.select_numbers,
              system_versions: this.select_versions
            }
          }
      ).then(
          response => {
            let res = JSON.parse(response.data)
            this.option.xAxis[0].data = res.xAxis;
            this.option.yAxis[0].max = Math.max(...[...res.series["feedback_count"], ...res.series["surgical_count"]]);
            this.option.yAxis[0].interval = Math.ceil(this.option.yAxis[0].max / 10);
            this.option.yAxis[1].max = Math.max(...res.series["ratio"]);
            this.option.yAxis[1].interval = this.option.yAxis[1].max / 10;
            this.option.series = [
              {
                name: '手术台数',
                type: 'bar',
                label: {
                  normal: {
                    show: true,
                    position: 'inside', // 显示位置
                    formatter: function (params) {
                      return params.value;
                    }
                  }
                },
                tooltip: {
                  valueFormatter: function (value) {
                    return value + ' 次';
                  }
                },
                data: res.series["surgical_count"]
              },
              {
                name: '客诉数量',
                type: 'bar',
                label: {
                  normal: {
                    show: true,
                    position: 'inside', // 显示位置
                    formatter: function (params) {
                      return params.value;
                    }
                  }
                },
                tooltip: {
                  valueFormatter: function (value) {
                    return value + ' 条';
                  }
                },
                data: res.series["feedback_count"]
              },
              {
                name: '客诉率',
                type: 'line',
                label: {
                  show: true,
                  position: 'top', // 显示位置
                  formatter: function (params) {
                    // 计算差值
                    return params.value.toFixed(2);
                    // let diff = 100 * (params.value - params.data.prev) / params.data.prev;
                    // let diffSign = diff > 0 ? '↑' : '↓';
                    // return diffSign + diff.toFixed(2) + "\n" + params.value.toFixed(2);
                  }
                },
                yAxisIndex: 1,
                tooltip: {
                  valueFormatter: function (value) {
                    return value + ' ';
                  }
                },
                data: res.series["ratio"].reduce(function (prev, curr, idx) {
                  prev.push({
                    value: curr,
                    prev: idx > 0 ? res.series["ratio"][idx - 1] : 0
                  });
                  return prev;
                }, [])
              }
            ];
            this.chart.setOption(this.option);
            this.chart.resize();
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
          })
    },
    selectChange() {
      axios.post('/feedback/figure/2/', {
            params: {
              date_list: this.date_range,
              product_models: this.select_models,
              sub_product_models: this.select_sub_models,
              feedback_type: this.select_feedback_type,
              equipment_numbers: this.select_numbers,
              system_versions: this.select_versions
            }
          }
      ).then(
          response => {
            let res = JSON.parse(response.data)
            this.option.xAxis[0].data = res.xAxis;
            this.option.yAxis[0].max = Math.max(...[...res.series["feedback_count"], ...res.series["surgical_count"]]);
            this.option.yAxis[0].interval = Math.ceil(this.option.yAxis[0].max / 10);
            this.option.yAxis[1].max = Math.max(...res.series["ratio"]);
            this.option.yAxis[1].interval = this.option.yAxis[1].max / 10;
            this.option.series = [
              {
                name: '手术台数',
                type: 'bar',
                label: {
                  normal: {
                    show: true,
                    position: 'inside', // 显示位置
                    formatter: function (params) {
                      return params.value;
                    }
                  }
                },
                tooltip: {
                  valueFormatter: function (value) {
                    return value + ' 次';
                  }
                },
                data: res.series["surgical_count"]
              },
              {
                name: '客诉数量',
                type: 'bar',
                label: {
                  normal: {
                    show: true,
                    position: 'inside', // 显示位置
                    formatter: function (params) {
                      return params.value;
                    }
                  }
                },
                tooltip: {
                  valueFormatter: function (value) {
                    return value + ' 条';
                  }
                },
                data: res.series["feedback_count"]
              },
              {
                name: '客诉率',
                type: 'line',
                label: {
                  show: true,
                  position: 'top', // 显示位置
                  formatter: function (params) {
                    // 计算差值
                    return params.value.toFixed(2);
                    // let diff = 100 * (params.value - params.data.prev) / params.data.prev;
                    // let diffSign = diff > 0 ? '↑' : '↓';
                    // return diffSign + diff.toFixed(2) + "\n" + params.value.toFixed(2);
                  }
                },
                yAxisIndex: 1,
                tooltip: {
                  valueFormatter: function (value) {
                    return value + ' ';
                  }
                },
                data: res.series["ratio"].reduce(function (prev, curr, idx) {
                  prev.push({
                    value: curr,
                    prev: idx > 0 ? res.series["ratio"][idx - 1] : 0
                  });
                  return prev;
                }, [])
              }
            ];
            this.chart.setOption(this.option);
            this.chart.resize();
          },
          // 失败
          error => {
            this.$message.error({message: error.response.data.message, showClose: true});
          })
    },
    initFigure() {
      const chartDom = document.getElementById('feedback-figure-2');
      this.chart = echarts.init(chartDom);
      this.chart.setOption(this.option);
      this.chart.resize();
      this.chart.on('click', function (params) {
        this.exportChartData([params.name]);
      }.bind(this));
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  },
  mounted() {
    this.initFigure()
    window.addEventListener('resize', this.handleResize)
    this.$nextTick(() => {
      this.chart.resize()
    })
  }
}
</script>

<style scoped lang="scss">
.transfer-footer {
  margin-left: 20px;
  padding: 6px 5px;
}

.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
  //line-height: 160px;
}

.el-date-editor--monthrange.el-input__inner {
  width: 400px;
}

#feedback-figure-2 {
  position: relative;
  height: 750px;
}

.el-checkbox {
    text-align: right;
    width: 100%;
    padding-right: 10px;
  }
</style>